#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/14  16:38
# @Author: 余浪人
# @email: yulangren520@gmail.com
from apps.cms import cms_bp
from flask import request, render_template, jsonify
from apps.forms.collector_form import Collector_Form, Auto_motion_Form, Proxy_Form
from apps.lib.public import add_data, edit_data, check_obj, real_delete_data, real_deletes, log, page_auto
from apps.models.collector_model import Collector_Model, db, Collect_History_Model, Collect_Proxy_Model
from flask_login import login_required
from apps.spiders.control.scheduler import spider_start


# 采集-列表
@cms_bp.route('/collector_list', endpoint='collector_list', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def collector_list():
    if request.method == 'DELETE':
        log('操作删除采集规则')
        return real_delete_data(Collector_Model, db, request.form.get('uid'))
    elif request.method == 'DELETE_S':
        log('操作批量删除采集规则')
        return real_deletes(Collector_Model, db, uid_s=list(eval(request.form.get('data_s') + ',')))
    paginate, page = page_auto(Collector_Model.query.filter(Collector_Model.status != 0))
    return render_template('sys_templates/collector_list.html', data_s=paginate, page=page, url='cms_bp.collector_list',
                           title='采集列表')


# 采集-新增
@cms_bp.route('/collector_add', endpoint='collector_add', methods=['GET', 'POST'])
@login_required
def collector_add():
    if request.method == 'POST':
        log('操作添加采集规则')
        return add_data(Collector_Model, Collector_Form, db)
    form = Collector_Form(request.form)
    return render_template('sys_templates/collector.html', form=form, title='新增采集')


# 采集-修改
@cms_bp.route('/collector_edit/<int:id>', endpoint='collector_edit', methods=['GET', 'POST'])
@login_required
def collector_edit(id):
    obj = Collector_Model.query.filter_by(id=id).first()
    if request.method == 'POST':
        log('操作修改采集规则')
        return edit_data(Collector_Form, Collector_Model, db, id)
    elif not check_obj(obj):
        form = Collector_Form(data=dict(obj))
        return render_template('sys_templates/collector.html', form=form, title=f'修改-{obj.project_name}')


# 采集-自动-列表
@cms_bp.route('/self_motion', endpoint='self_motion', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def self_motion():
    if request.method == 'DELETE':
        obj = Collector_Model.query.filter_by(id=request.form.get('uid')).first()
        if not check_obj(obj) and obj:
            obj.set_attrs({"tim_acquisition": 0})
            db.session.commit()
            return jsonify({"status": 0})
        return jsonify({"status": 1})
    elif request.method == 'DELETE_S':
        try:
            for uid in list(eval(request.form.get('data_s') + ',')):
                obj = Collector_Model.query.filter_by(id=uid).first()
                if not check_obj(obj) and uid:
                    obj.set_attrs({"tim_acquisition": 0})
            db.session.commit()
            return jsonify({"status": 0})
        except:
            return jsonify({"status": 1})
    data_s = Collector_Model.query.order_by(db.desc(Collector_Model.id)).filter(Collector_Model.status != 0,
                                                                                Collector_Model.tim_acquisition == 1)
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/collector_auto_list.html', data_s=paginate, page=page,
                           url='cms_bp.self_motion',
                           title='自动采集列表')


# 采集-自动采集时间
@cms_bp.route('/self_motion_edit/<int:id>', endpoint='self_motion_edit', methods=['GET', 'POST'])
@login_required
def self_motion_edit(id):
    obj = Collector_Model.query.filter_by(id=id).first()
    if request.method == 'POST':
        return edit_data(Auto_motion_Form, Collector_Model, db, id)
    elif not check_obj(obj):
        form = Auto_motion_Form(data=dict(obj))
        return render_template('sys_templates/self_motion.html', form=form, title='自动任务设置')


# 采集-历史记录
@cms_bp.route('/collect_history', endpoint='collect_history', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def collect_history():
    if request.method == 'DELETE':
        return real_delete_data(Collect_History_Model, db, request.form.get('uid'))
    elif request.method == 'DELETE_S':
        return real_deletes(Collect_History_Model, db, uid_s=list(eval(request.form.get('data_s') + ',')))
    data_s = Collect_History_Model.query.order_by(db.desc(Collect_History_Model.id))
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/collect_history_list.html', data_s=paginate, page=page,
                           url='cms_bp.collect_history',
                           title='采集历史列表')


# 采集-代理IP
@cms_bp.route('/collect_proxy', endpoint='collect_proxy', methods=['GET', 'POST'])
@login_required
def collect_proxy():
    obj = Collect_Proxy_Model.query.filter().first()
    if request.method == 'POST':
        return edit_data(Proxy_Form, Collect_Proxy_Model, db, obj.id)
    form = Proxy_Form(data=dict(obj))
    return render_template('sys_templates/proxy_set.html', form=form)


# 采集-单点采集
@cms_bp.route('/collect_new/<uuid>', endpoint='collect_new', methods=['GET', 'POST'])
@login_required
def collect_new(uuid: str):
    coll_obj = Collector_Model.query.filter_by(uuid=uuid).first()
    if not check_obj(coll_obj):
        spider_start(coll_obj)
        return '<div><div style="width:300px;margin: auto;  position: absolute; "><h2>采集完成!</h2></div></div>'
    return '<div><div style="width:300px;margin: auto;  position: absolute; "><h2>规则验证失败!</h2></div></div>'
